package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.bean.TradeSourceBean;
import com.atguigu.util.ClickHouseUtil_hjy;
import com.atguigu.util.DateFormatUtil_hjy;
import com.atguigu.util.MyKafkaUtil_hjy;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author hjy
 * @create 2023/3/30 9:58
 */
public class Dws_TradeSourceWindow {
    public static void main(String[] args) throws Exception {

        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://47.102.112.46:8020/gmall-flink/check/baseLogApp");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka主题（dwd_test_exam_question）消费数据
        String topic="dwd_trade_source_ready";
        String groupId="dws_trade_source_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil_hjy.getKafkaConsumer(topic, groupId));
        //todo 3 将数据转为JSONObj 并过滤 并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWM = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject record = JSON.parseObject(value);
                out.collect(record);
            }
        })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("create_time");
                            }
                        })));
        //todo 4 按照uid分组
        KeyedStream<JSONObject, String> keyedByUserIdDS = jsonObjWithWM.keyBy(value -> value.getString("user_id"));
        //todo 5 转为javaBean对象
        SingleOutputStreamOperator<TradeSourceBean> javaBeanWithUvCt = keyedByUserIdDS.map(new RichMapFunction<JSONObject, TradeSourceBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlCfg = StateTtlConfig.newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();

                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("exist", String.class);
                valueStateDescriptor.enableTimeToLive(ttlCfg);

                valueState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public TradeSourceBean map(JSONObject value) throws Exception {
                String lastDt = valueState.value();
                Long ts = value.getLong("create_time");
                String curtDt = DateFormatUtil_hjy.toDate(ts);
                Long uv = 0L;
                if (lastDt == null || !lastDt.equals(curtDt)) {
                    valueState.update(curtDt);
                    uv = 1L;
                }

                return TradeSourceBean.builder()
                        .orderID(value.getString("order_id"))
                        .sourceID(value.getString("sc"))
                        .amountSum(value.getBigDecimal("origin_amount"))
                        .orderUvCt(uv)
                        .build();
            }
        });
        //todo 6 按照orderId分组去重
        KeyedStream<TradeSourceBean, String> keyedByOrderIdDS = javaBeanWithUvCt.keyBy(TradeSourceBean::getOrderID);

        //todo 7 给javaBean赋值
        SingleOutputStreamOperator<TradeSourceBean> javaBeanDS = keyedByOrderIdDS.map(new RichMapFunction<TradeSourceBean, TradeSourceBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {

                StateTtlConfig ttlCfg = StateTtlConfig.newBuilder(Time.seconds(5))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();
                ValueStateDescriptor<String> orderId = new ValueStateDescriptor<>("order_id", String.class);
                orderId.enableTimeToLive(ttlCfg);
                valueState = getRuntimeContext().getState(orderId);
            }

            @Override
            public TradeSourceBean map(TradeSourceBean value) throws Exception {
                String exist = valueState.value();
                Long orderCt = 0L;
                if (exist == null) {
                    orderCt = 1L;
                    valueState.update("1");
                }
                value.setOrderCt(orderCt);
                return value;
            }
        });
        //todo 8 按照来源分组
        KeyedStream<TradeSourceBean, String> keyedStream = javaBeanDS.keyBy(TradeSourceBean::getSourceID);

        //todo 9 开窗聚合
        SingleOutputStreamOperator<TradeSourceBean> reduceDS = keyedStream.window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TradeSourceBean>() {
                    @Override
                    public TradeSourceBean reduce(TradeSourceBean value1, TradeSourceBean value2) throws Exception {
                        value1.setAmountSum(value1.getAmountSum().add(value2.getAmountSum()));
                        value1.setOrderCt(value1.getOrderCt() + value2.getOrderCt());
                        value1.setOrderUvCt(value1.getOrderUvCt() + value2.getOrderUvCt());
                        return value1;
                    }
                }, new WindowFunction<TradeSourceBean, TradeSourceBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeSourceBean> input, Collector<TradeSourceBean> out) throws Exception {

                        TradeSourceBean next = input.iterator().next();
                        out.collect(MyWindowFunction.getWindow(next, window));
                    }
                });

        //todo 10 关联维表
        SingleOutputStreamOperator<TradeSourceBean> resultDS = AsyncDataStream.unorderedWait(reduceDS, new AsyncDimFunction<TradeSourceBean>("DIM_BASE_SOURCE") {
            @Override
            public void getDimInfo(TradeSourceBean input, JSONObject dimInfo) {
                String name = dimInfo.getString("SOURCE_SITE");
                input.setSourceName(name);
            }

            @Override
            public String getId(TradeSourceBean input) {
                return input.getSourceID();
            }

            @Override
            public String getFilterId() {
                return "id";
            }
        }, 60, TimeUnit.SECONDS);

        //todo 11 写出数据到clickHouse
        resultDS.print("resultDS>>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil_hjy.getClickHouseSink("insert into dws_trade_source_window values(?,?,?,?,?,?,?)"));

        //todo 12 启动程序
        env.execute();
    }
}
